import * as fs from 'fs';
import * as path from 'path';
import { app } from 'electron';

/**
 * 历史记录服务类，用于管理计算历史记录
 */
export class HistoryService {
  private static getHistoryFilePath(): string {
    // 获取应用数据目录
    const userDataPath = app.getPath('userData');
    const historyFilePath = path.join(userDataPath, 'calculationHistory.json');
    return historyFilePath;
  }

  /**
   * 保存计算记录
   * @param record 计算记录
   * @returns 保存结果
   */
  static async saveRecord(record: any) {
    try {
      const historyFilePath = this.getHistoryFilePath();
      
      // 读取现有历史记录
      let history: any[] = [];
      if (fs.existsSync(historyFilePath)) {
        const data = fs.readFileSync(historyFilePath, 'utf8');
        history = JSON.parse(data);
      }
      
      // 添加新记录（添加时间戳）
      const newRecord = {
        ...record,
        id: Date.now().toString(),
        timestamp: new Date().toISOString()
      };
      
      history.push(newRecord);
      
      // 保存到文件
      fs.writeFileSync(historyFilePath, JSON.stringify(history, null, 2));
      
      return { success: true, data: newRecord };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 获取所有计算记录
   * @returns 计算记录列表
   */
  static async getRecords() {
    try {
      const historyFilePath = this.getHistoryFilePath();
      
      if (!fs.existsSync(historyFilePath)) {
        return { success: true, data: [] };
      }
      
      const data = fs.readFileSync(historyFilePath, 'utf8');
      const history = JSON.parse(data);
      
      // 按时间倒序排列（最新的在前面）
      history.sort((a: any, b: any) => {
        return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
      });
      
      return { success: true, data: history };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 删除指定计算记录
   * @param id 记录ID
   * @returns 删除结果
   */
  static async deleteRecord(id: string) {
    try {
      const historyFilePath = this.getHistoryFilePath();
      
      if (!fs.existsSync(historyFilePath)) {
        return { success: true, message: '记录不存在' };
      }
      
      const data = fs.readFileSync(historyFilePath, 'utf8');
      let history = JSON.parse(data);
      
      // 过滤掉要删除的记录
      history = history.filter((record: any) => record.id !== id);
      
      // 保存更新后的记录
      fs.writeFileSync(historyFilePath, JSON.stringify(history, null, 2));
      
      return { success: true, message: '记录删除成功' };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }

  /**
   * 清空所有计算记录
   * @returns 清空结果
   */
  static async clearAllRecords() {
    try {
      const historyFilePath = this.getHistoryFilePath();
      
      if (fs.existsSync(historyFilePath)) {
        fs.unlinkSync(historyFilePath);
      }
      
      return { success: true, message: '所有记录已清空' };
    } catch (error: any) {
      return { success: false, error: error.message };
    }
  }
}